import '@/assets/mapbox/libs/draw/mapbox-gl-draw.js'
import * as turf from '@turf/turf';
import PlotBaseClass from '@/assets/js/plot/AreaPlotBase.js'

/**
         * Package: StraightArrow
         * 直箭头：1.控制点组；2.构成的所有点部分
         * 方法：用于通过控制点计算箭头的所有绘制点
         */
const doubleClickZoom = {
  enable: ctx => {
    setTimeout(() => {
      // First check we've got a map and some context.
      if (
        !ctx.map ||
        !ctx.map.doubleClickZoom ||
        !ctx._ctx ||
        !ctx._ctx.store ||
        !ctx._ctx.store.getInitialConfigValue
      )
        return;
      // Now check initial state wasn't false (we leave it disabled if so)
      if (!ctx._ctx.store.getInitialConfigValue("doubleClickZoom")) return;
      ctx.map.doubleClickZoom.enable();

      //state.controlPoints =[];
    }, 0);
  },
  disable(ctx) {
    setTimeout(() => {
      if (!ctx.map || !ctx.map.doubleClickZoom) return;
      // Always disable here, as it's necessary in some cases.
      ctx.map.doubleClickZoom.disable();
    }, 0);
  }
};

const DrawGeoBezierCurve2 = {
  // When the mode starts this function will be called.
  onSetup: function(opts) {
    const GeoBezierCurve2 = this.newFeature({
      type: "Feature",
      properties: {},
      geometry: {
        type: "Line",
        coordinates: [[]]
      }
    });
    this.addFeature(GeoBezierCurve2);
    
    this.clearSelectedFeatures();
    doubleClickZoom.disable(this);
    this.updateUIClasses({ mouse: "add" });
    this.setActionableState({
      trash: true
    });
    return {
      GeoBezierCurve2
    };
  },
  // support mobile taps
  onTap: function(state, e) {
    // emulate 'move mouse' to update feature coords
    if (state.controlPoints) this.onMouseMove(state, e);
    // emulate onClick
    this.onClick(state, e);
  },
  // Whenever a user clicks on the map, Draw will call `onClick`（箭头的起始点）
  onClick: function(state, e) {
    // if state.startPoint exist, means its second click
    //change to  simple_select mode（继续画，双击结束）
    var point = this.newFeature({
    type: 'Feature',
    properties: {
      
    },
    geometry: {
      type: 'Point',
      coordinates: [e.lngLat.lng, e.lngLat.lat]
    }
  });
    this.addFeature(point); //显示点

   if (
      state.controlPoints &&
      state.controlPoints[state.controlPoints.length-1].x !== e.lngLat.lng &&
      state.controlPoints[state.controlPoints.length-1].y !== e.lngLat.lat
    ) {
      this.updateUIClasses({ mouse: "pointer" });
     
      this.changeMode("simple_select", { featuresId: state.straightArrow.id });
    }

    const startPoint = [];
    state.controlPoints = startPoint;
    state.controlPoints.push({x:e.lngLat.lng, y:e.lngLat.lat});//箭头的控制点
    
  },
  onMouseMove: function(state, e) {
    // if startPoint, update the feature coordinates, using the bounding box concept
    // we are simply using the startingPoint coordinates and the current Mouse Position
    // coordinates to calculate the bounding box on the fly, which will be our rectangle  有起始控制点，通过鼠标停留的改点计算箭头样式显示在地图上，随着移动更新
    if (state.controlPoints) {
       if(state.controlPoints.length  != 0 ){
        const arrowpnts = this.cloneControlPoints(state.controlPoints);
        arrowpnts.push({x:e.lngLat.lng, y:e.lngLat.lat})
        const sevenpnts =  this.calculateParts(arrowpnts);
         
        for(var i=0;i < sevenpnts.length;i++){

           // state.straightArrow.coordinates.push([ sevenpnts[i].x,sevenpnts[i].y]);
            
           state.straightArrow.updateCoordinate("0."+i, sevenpnts[i].x, sevenpnts[i].y ); 
           //state.straightArrow.updateCoordinate("0.2", e.lngLat.lng, e.lngLat.lat); // maxX, maxY
         }
       }
      else{
        //没有控制点的情况
    }
    }
  },
  // keyboard triger while focused on the map：ESC:27
  onKeyUp: function(state, e) {
    if (e.keyCode === 27) return this.changeMode("simple_select");
  },
  onStop: function(state) {
    doubleClickZoom.enable(this);
    this.updateUIClasses({ mouse: "none" });
    this.activateUIButton();

    // check to see if we've deleted this feature
    if (this.getFeature(state.straightArrow.id) === undefined) return;

    //remove last added coordinate 移除最后一个点
   // state.straightArrow.removeCoordinate("0.4"); 
    if (state.straightArrow.isValid()) {
      this.map.fire("draw.create", {
        features: [state.straightArrow.toGeoJSON()]
      });
    } else {
      this.deleteFeature([state.straightArrow.id], { silent: true });
      this.changeMode("simple_select", {}, { silent: true });
    }
  },
  toDisplayFeatures: function(state, geojson, display) {
    const isActivePolygon = geojson.properties.id === state.straightArrow.id;
    geojson.properties.active = isActivePolygon ? "true" : "false";
    if (!isActivePolygon) return display(geojson);
  
    // Only render the rectangular polygon if it has the starting point
    if (!state.controlPoints) return;
    return display(geojson);
  },
  onTrash: function(state) {
    this.deleteFeature([state.straightArrow.id], { silent: true });
    this.changeMode("simple_select");
  },


  };

      

       
export default GeoBezierCurve2;